﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.TenPayV3.Apis.BasePay;
using SportsPlatform.Base;
using SportsPlatform.Dto.WeiXinPay;
using SportsPlatform.Filters;
using SportsPlatform.Query.WeiXinPay;
using SportsPlatform.WeiXinPay.IWeiXinPay;
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.Controllers
{
    /// <summary>
    /// 小程序微信支付接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [AllowAnonymousAttribute]
    public class WeiXinTenPayV3Controller : SportsPlatformControllerBase
    {
        private IWeiXinTenPayV3Service _weixinpay;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="weixinpay"></param>
        public WeiXinTenPayV3Controller(IWeiXinTenPayV3Service weixinpay)
        {
            _weixinpay = weixinpay;
        }



        /// <summary>
        ///  根据Code获取OpenId
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public GetCodeToOpenIdDto GetCodeToOpenId([FromBody] GetCodeToOpenIdQuery query)
        {
            return _weixinpay.GetCodeToOpenId(query);
        }

        /// <summary>
        /// 预下单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<JsApiPreOrderDto>> JsApiPreOrder([FromBody] JsApiPreOrderQuery query)
        {
            return await _weixinpay.JsApiPreOrder(query);
        }

        /// <summary>
        /// 根据商户订单Id获取订单信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<OrderReturnJson>> OrderQueryByOutTradeNo([FromBody] GetOrderInfoQuery query)
        {
            return await _weixinpay.OrderQueryByOutTradeNo(query);
        }

        /// <summary>
        /// 根据微信支付订单Id获取订单信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<OrderReturnJson>> OrderQueryByTransactionId([FromBody] GetOrderInfoQuery query)
        {
            return await _weixinpay.OrderQueryByTransactionId(query);
        }

        /// <summary>
        ///退款 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<RefundDto>> Refund([FromBody] RefundQuery query)
        {
            return await _weixinpay.Refund(query);
        }

        /// <summary>
        ///退款查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<RefundInfoDto>> RefundQuery([FromBody] RefundQueryQuery query)
        {
            return await _weixinpay.RefundQuery(query);
        }

        ///// <summary>
        ///// trade_no 和 transaction_id 对照表
        ///// TODO：可以放入缓存，设置有效时间
        ///// </summary>
        //public static ConcurrentDictionary<string, string> TradeNumberToTransactionId = new ConcurrentDictionary<string, string>();

        ///// <summary>
        ///// JS-SDK支付回调地址（在下单接口中设置的 notify_url）
        ///// </summary>
        ///// <returns></returns>
        //public async Task<IActionResult> PayNotifyUrl()
        //{
        //    try
        //    {
        //        //获取微信服务器异步发送的支付通知信息
        //        var resHandler = new TenPayNotifyHandler(HttpContext);
        //        var orderReturnJson = await resHandler.AesGcmDecryptGetObjectAsync<OrderReturnJson>();

        //        //记录日志
        //        Senparc.Weixin.WeixinTrace.SendCustomLog("PayNotifyUrl 接收到消息", orderReturnJson.ToJson(true));

        //        //演示记录 transaction_id，实际开发中需要记录到数据库，以便退款和后续跟踪
        //        TradeNumberToTransactionId[orderReturnJson.out_trade_no] = orderReturnJson.transaction_id;

        //        //获取支付状态
        //        string trade_state = orderReturnJson.trade_state;

        //        //验证请求是否从微信发过来（安全）
        //        NotifyReturnData returnData = new();

        //        //验证可靠的支付状态
        //        if (orderReturnJson.VerifySignSuccess == true && trade_state == "SUCCESS")
        //        {
        //            returnData.code = "SUCCESS";//正确的订单处理
        //            /* 提示：
        //                * 1、直到这里，才能认为交易真正成功了，可以进行数据库操作，但是别忘了返回规定格式的消息！
        //                * 2、上述判断已经具有比较高的安全性以外，还可以对访问 IP 进行判断进一步加强安全性。
        //                * 3、下面演示的是发送支付成功的模板消息提示，非必须。
        //                */
        //        }
        //        else
        //        {
        //            returnData.code = "FAILD";//错误的订单处理
        //            returnData.message = "验证失败";

        //            //此处可以给用户发送支付失败提示等
        //        }

        //        #region 记录日志（也可以记录到数据库审计日志中）

        //        var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
        //        if (!Directory.Exists(logDir))
        //        {
        //            Directory.CreateDirectory(logDir);
        //        }

        //        var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));

        //        using (var fileStream = System.IO.File.OpenWrite(logPath))
        //        {
        //            var notifyJson = orderReturnJson.ToString();
        //            await fileStream.WriteAsync(Encoding.Default.GetBytes(notifyJson), 0, Encoding.Default.GetByteCount(notifyJson));
        //            fileStream.Close();

        //        }
        //        #endregion

        //        //https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtml
        //        return Json(returnData);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
        //        throw;
        //    }
        //}
    }
}
